﻿using Newtonsoft.Json;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace MyOCR.Translate
{
    class YouDao_TranslateHandle : TranslateHandle
    {
        string salt;
        string curtime;
        public override string GetResult()
        {
            var lst = new List<string>();
            var content = GetJson();
            dynamic json = JsonConvert.DeserializeObject(content);

            try
            {
                foreach (var item in json.translation)
                {
                    lst.Add(item.ToString());
                }

                return string.Join("\r\n", lst);
            }
            catch (Exception)
            {
                return "错误码 ："+json.errorCode + ",请检查密钥或网络状态";
            }

        }

        protected override string GetJson()
        {
            var client = new RestClient("https://openapi.youdao.com/api");
            var request = new RestRequest(Method.POST);
            salt = DateTime.Now.Millisecond.ToString();
            TimeSpan ts = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc));
            long millis = (long)ts.TotalMilliseconds;
            curtime = Convert.ToString(millis / 1000);
            string sign = getSign();

            request.AddParameter("from", "auto");
            request.AddParameter("to", "auto");
            request.AddParameter("signType", "v3");
            request.AddParameter("curtime", curtime);
            request.AddParameter("q", need_Tslt);
            request.AddParameter("appKey", Program._config.YouDao_App_Key);
            request.AddParameter("salt", salt);
            request.AddParameter("sign", sign);

            IRestResponse response = client.Execute(request);

            return response.Content;
        }

        protected override string getSign()
        {
            HashAlgorithm algorithm = new SHA256CryptoServiceProvider();
            string signStr = Program._config.YouDao_App_Key + Truncate(need_Tslt) + salt + curtime + Program._config.YouDao_App_Secret;
            Byte[] inputBytes = Encoding.UTF8.GetBytes(signStr);
            Byte[] hashedBytes = algorithm.ComputeHash(inputBytes);
            return BitConverter.ToString(hashedBytes).Replace("-", "");
        }

        protected static string Truncate(string q)
        {
            if (q == null)
            {
                return null;
            }
            int len = q.Length;
            return len <= 20 ? q : (q.Substring(0, 10) + len + q.Substring(len - 10, 10));
        }
    }
}
